package de.dopichaj.labrador.search.hit;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import de.dopichaj.labrador.search.QueryCategory;


public final class HitCategoryScoreMap {

    private final ArrayList<CategorizedHit> hits = new ArrayList<CategorizedHit>();
    private final int maxCategoryIndex;
    private final Collection<QueryCategory> categories;
    private final QueryCategory singleCategory;

    /**
     * Constructs a HitCategoryScoreMap where the given categories are allowed.
     */
    public HitCategoryScoreMap(Collection<QueryCategory> categories) {
        if (categories.size() > 1) {
            this.categories = categories;
            this.singleCategory = null;
        } else {
            singleCategory = categories.iterator().next();
            this.categories = Collections.singleton(singleCategory);
        }
        int max = 0;
        for (QueryCategory category : categories) {
            if (category.getIndex() > max) {
                max = category.getIndex();
            }
        }
        maxCategoryIndex = max;
    }
    
    /**
     * Sets the score of the hit with the given fragment ID in the given category.
     */
    public synchronized void setScore(QueryCategory category,
        int fragmentId, float score) {
        
        // make sure the category exists
        if (!categories.contains(category)) {
            throw new IllegalArgumentException(
                "Tried to set score on non-existent category " + category);
        }
        
        // set the category score
        CategorizedHit hit = makeCategorizedHit(fragmentId);
        hits.add(hit);
        hit.setCategoryScore(category, score);
    }
    
    private CategorizedHit makeCategorizedHit(int fragmentId) {
        if (maxCategoryIndex == 0) {
            return new SingleCategoryHit(fragmentId);
        } else {
            return new MultiCategoryHit(
                fragmentId, new float[maxCategoryIndex + 1]);
        }
    }

    /**
     * Close this map. Further updates are not allowed.
     */
    public void close() {
        hits.trimToSize();
        Collections.sort(hits);
    }

    public float highestScore(Collection<Integer> ids) {
        
        int min = Integer.MAX_VALUE;
        int max = 0;
        for (int id : ids) {
            if (id < min) {
                min = id;
            } else if (id > max) {
                max = id;
            }
        }
        return highestScore(min, max);
    }

    /**
     * Gets the highest score in any category of the fragments in the given ID
     * range.
     */
    public float highestScore(int minId, int maxId) {
        float highScore = 0.0f;
        final int end = findIndex(maxId);
        for (int i = findIndex(minId); i < end; i++) {
            
            CategorizedHit hit = hits.get(i);
            if (singleCategory == null) {
                for (QueryCategory category : categories) {
                    if (hit.getCategoryScore(category) > highScore) {
                        highScore = hit.getCategoryScore(category);
                    }
                }
            } else {
                if (hit.getCategoryScore(singleCategory) > highScore) {
                    highScore = hit.getCategoryScore(singleCategory);
                }
            }
        }
        return highScore;
    }

    private int findIndex(int fragmentId) {
        return Collections.binarySearch(hits, new SingleCategoryHit(fragmentId));
    }
    
    /**
     * Associates the given fragment ID with the given hit.
     */
    public void associate(int fragmentId, Hit hit) {
        hits.get(findIndex(fragmentId)).setHit(hit);
    }

    private static final class IdWrapper extends AbstractList<Integer> {

        private final List<CategorizedHit> hits;

        public IdWrapper(List<CategorizedHit> hits) {
            this.hits = hits;
        }
        
        private static final class IdIterator implements Iterator<Integer> {
            
            private final Iterator<CategorizedHit> it;
            
            public IdIterator(Iterator<CategorizedHit> iterator) {
                this.it = iterator;
            }

            public boolean hasNext() {
                return it.hasNext();
            }

            public Integer next() {
                return it.next().getFragmentId();
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        }
        
        @Override
        public Iterator<Integer> iterator() {
            return new IdIterator(hits.iterator());
        }

        @Override
        public int size() {
            return hits.size();
        }

        @Override
        public Integer get(int index) {
            return hits.get(index).getFragmentId();
        }
    }
    
    /**
     * Gets all the fragment IDs. 
     */
    public List<Integer> getHits() {
        return new IdWrapper(hits);
    }
    
    public List<CategorizedHit> getHitsH() {
        return Collections.unmodifiableList(hits);
    }

    public Collection<QueryCategory> getCategories() {
        return categories;
    }

    public CategorizedHit getHit(int luceneId) {
        return hits.get(findIndex(luceneId));
    }
}
/*
Copyright (c) 2005 Benedikt Eger
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/